import {
    setFormId
} from '../../api/api.js';
import {
    getCategoryList,
    getProductslist,
    postCartAdd
} from '../../api/store.js';
import {
    getCartCounts
} from '../../api/order.js';
import Util from '../../utils/util.js';
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        iShidden: true,
        navlist: [],
        productList: [],
        navActive: 0,
        navIndex: 0,
        food: [],
        parameter: {
            'navbar': '1',
            'return': '0',
            'title': '产品分类'
        },
        navH: "",
        number: "",
        currentData: 0,
        currentIndex: 'a',
        cate_id: 0,
        children: [],
        daodi: 0,
        daoding: 1,
        pullup: '',
        dropdown: '',
        scrollTop: -1,
        where: {
            sid: 0,
            keyword: '',
            priceOrder: '',
            salesOrder: '',
            news: 0,
            page: 1,
            limit: 999,
            cid: 0,
            longitude: '',
            latitude: '',
            district: ''
        },
        location: ''
    },
    onLoadFun: function() {
        //   this.onLoad();
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(res) {
        Util.getlocation(this)
        if (app.globalData.cate_id) {
            this.setData({
                cate_id: app.globalData.cate_id
            });
            this.getAllCategory();
            app.globalData.cate_id = '';
        } else {
            //扫码携带参数处理
            if (res.scene) {
                var value = Util.getUrlParams(decodeURIComponent(res.scene));
                this.setData({
                    cate_id: value.cate_id
                });
            }
            this.getAllCategory();
        }
        this.infoScroll();
    },
    allowFun: function() {
        this.onLoad();
    },
    tap: function(e) {
        const that = this;
        var id = e.currentTarget.dataset.id;
        var index = e.currentTarget.dataset.index;
        that.switchOne(id, index);
        that.infoScroll();
    },
    infoScroll: function() {
        var that = this;
        that.setData({
            navH: app.globalData.navHeight,
        })
        //设置商品列表高度
        wx.getSystemInfo({
            success: function(res) {
                that.setData({
                    height: (res.windowHeight) * (750 / res.windowWidth) - 96 - app.globalData.navHeight,
                    true1: true
                    //res.windowHeight:获取整个窗口高度为px，*2为rpx；98为头部占据的高度；
                })
            },
        });
        var height = 0;

    },
    getAllCategory: function() {
        var that = this;
        var cate_id = that.data.cate_id;
        getCategoryList({
            latitude: that.data.where.latitude,
            longitude: that.data.where.longitude,
            district: that.data.where.district
        }).then(res => {
            that.setData({
                productList: res.data,
                ['where.cid']: cate_id != 0 ? cate_id : res.data[0].id,
                navActive: cate_id != 0 ? cate_id : res.data[0].id
            });
            if (cate_id != 0) {
                for (var i = 0; i < res.data.length; i++) {
                    if (cate_id == res.data[i].id) {
                        var nextnavIndex = i;
                    }
                }
                that.switchOne(cate_id, nextnavIndex);
            } else {
                that.getProductslist();
                that.setChildren();
            }
        })
    },
    setChildren: function() {
        this.setData({
            children: this.data.productList[0].children
        });
    },
    getProductslist: function() {
        var that = this;
        //获取选中分类下商品
        getProductslist(that.data.where).then(res => {
            that.setData({
                food: res.data
            })
        })
    },
    searchSubmitValue: function(e) {
        var that = this;
        setFormId(e.detail.formId).then(res => {}).catch(err => {});
        if (e.detail.value.length > 0)
            wx.navigateTo({
                url: '/pages/goods_list/goods_list?searchValue=' + e.detail.value
            })
        else
            return app.Tips({
                title: '请填写要搜索的产品信息'
            });
    },
    checkCurrent: function(e) {
        const that = this;
        that.setData({
            currentData: e.target.dataset.id,
            currentIndex: e.target.dataset.index,
            ['where.sid']: e.target.dataset.id,
            ['where.page']: 1,
            daodi: 0,
            daoding: 1,
            food: [],
            scrollTop: 0,
            pullup: '',
            pulldown: ''
        })
        that.getProductslist();
    },
    details: function(e) {
        wx.navigateTo({
            url: '/pages/goods_details/index?id=' + e.currentTarget.dataset.id,
        })
    },
    shopping: function(e) {
        if (app.globalData.isLog === false) {
            this.setData({
                isAuto: true,
                iShidden: false
            });
        } else {
            postCartAdd({
                productId: e.currentTarget.dataset.id,
                cartNum: 1,
                uniqueId: '',
                'new': 0,
                'quick': 1,
            }).then(res => {
                app.Tips({
                    title: '添加购物车成功',
                })
                this.getCartCount();
            }).catch(err => {
                return app.Tips({
                    title: err
                });
            })
        }

    },
    getCartCount: function() {
        var that = this;
        getCartCounts({}).then(res => {
            app.globalData.cart_count = res.data.count.toString();
            if (app.globalData.cart_count > 0) {
                wx.setTabBarBadge({
                    index: 3,
                    text: app.globalData.cart_count
                })
            }

        });
    },
    /**
     * 一级分类切换操作
     */
    switchOne: function(id, index) {
        const that = this;
        that.setData({
            navActive: id,
            navIndex: index,
            currentIndex: 'a',
            children: that.data.productList[index].children,
            ['where.cid']: that.data.productList[index].id,
            ['where.page']: 1,
            ['where.sid']: '',
            daodi: 0,
            daoding: 1,
            scrollTop: 0,
            pullup: '',
            pulldown: ''
        });
        if (index !== "" || index !== null) {
            that.setData({
                currentData: 0,
                food: []
            })
        }

        that.getProductslist();
    },
    /**
     * 一级分类切换操作
     */
    switchTwo: function(id, index) {
        const that = this;
        that.setData({
            currentData: id,
            currentIndex: index,
            ['where.sid']: id,
            ['where.page']: 1,
            food: [],
            daodi: 0,
            daoding: 1,
            scrollTop: 0,
            pullup: '',
            pulldown: ''
        })

        that.getProductslist();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        location = wx.getStorageSync('location');
        if (app.globalData.cate_id) {
            this.onLoad();
        } else {
            if (this.data.where.district == '' || this.data.where.district == undefined || this.data.where.district != location.address_component.district) {
                Util.getlocation(this)
                this.getAllCategory();
            }
        }
        if (app.globalData.isLog == true) {
            this.getCartCount();
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    scrollToLower: function() {
        this.setData({
            daodi: 1
        })
    },
    scrollToLower1: function() {
        var that = this;
        var navIndex = that.data.navIndex; //一级分类当前下标
        var currentIndex = that.data.currentIndex; //二级分类当前下标
        var catelength = that.data.productList.length - 1; //分类数量
        var nextnavIndex = navIndex + 1;
        var children = that.data.children; //当前二级分类
        var sonlength = children.length - 1; //当前二级分类数量
        var nextcurrentIndex = currentIndex + 1;
        //判断是否是最后一个分类
        if (navIndex < catelength) {
            //当二级分类选择时
            if (currentIndex == 'a') {
                that.switchOne(that.data.productList[nextnavIndex].id, nextnavIndex);
            } else {
                if (currentIndex < sonlength) {
                    that.switchTwo(children[nextcurrentIndex].id, nextcurrentIndex);
                } else {
                    that.switchOne(that.data.productList[nextnavIndex].id, nextnavIndex);
                }

            }
        } else {
            //当二级分类选择时
            if (currentIndex != 'a') {
                if (currentIndex < sonlength) {
                    that.switchTwo(children[nextcurrentIndex].id, nextcurrentIndex);
                }
            }
        }

    },
    scrollToLower2: function() {
        var that = this;
        var navIndex = that.data.navIndex; //一级分类当前下标
        var currentIndex = that.data.currentIndex; //二级分类当前下标
        var catelength = that.data.productList.length - 1; //分类数量
        var prevnavIndex = navIndex - 1;
        var children = that.data.children; //当前二级分类
        var sonlength = children.length - 1; //当前二级分类数量
        var prevcurrentIndex = currentIndex - 1;
        //判断是否是第一个分类
        if (navIndex > 0) {
            if (currentIndex == 'a') {
                that.switchOne(that.data.productList[prevnavIndex].id, prevnavIndex);
            } else {
                if (currentIndex > 0) {
                    that.switchTwo(children[prevcurrentIndex].id, prevcurrentIndex);
                } else {
                    that.switchOne(that.data.productList[prevnavIndex].id, prevnavIndex);
                }

            }
        } else {
            //当二级分类选择时
            if (currentIndex != 'a') {
                if (currentIndex > 0) {
                    that.switchTwo(children[prevcurrentIndex].id, prevcurrentIndex);
                }
            }
        }

    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },
    //滑动移动事件
    handletouchmove1: function(event) {
        if (this.data.daodi == 0) {
            return;
        }
        var currentX = event.touches[0].pageX
        var currentY = event.touches[0].pageY
        var tx = currentX - this.data.lastX
        var ty = currentY - this.data.lastY
        //左右方向滑动
        var text;
        if (ty < 0)
            text = "向上滑动"
        else if (ty > 0)
            text = "向下滑动"

        this.setData({
            pullup: text
        })
        //将当前坐标进行保存以进行下一次计算
        this.data.lastX = currentX
        this.data.lastY = currentY


    },
    bindscroll: function(e) {
        //判断是否到顶
        if (e.detail.scrollTop <= 0) {
            this.setData({
                daoding: 1
            })
        } else if (e.detail.scrollTop > 0) {
            this.setData({
                daoding: 0
            })
        }
        //  else if (e.detail.scrollTop < -100) {
        //    this.scrollToLower2();
        // }
    },
    //滑动开始事件
    handletouchtart: function(event) {
        if (this.data.daodi == 0) {
            return;
        }
        this.data.lastX = event.touches[0].pageX
        this.data.lastY = event.touches[0].pageY
    },
    //滑动结束事件
    handletouchend1: function(event) {
        if (this.data.daodi == 0) {
            return;
        }
        if (this.data.pullup == '向上滑动') {
            this.scrollToLower1();
        }
        this.data.currentGesture = 0;
    },
    //触摸开始
    handletouchstart: function(event) {},
    //触摸移动
    handletouchmove: function(event) {
        if (this.data.daoding == 0) {
            return;
        }
        var currentX = event.touches[0].pageX
        var currentY = event.touches[0].pageY
        var tx = currentX - this.data.lastX
        var ty = currentY - this.data.lastY
        var text = ""

        //上下方向滑动

        if (ty < 0)
            text = "向上滑动"
        else if (ty > 0)
            text = "向下滑动"

        this.setData({
            pulldown: text
        })
        //将当前坐标进行保存以进行下一次计算
        this.data.lastX = currentX
        this.data.lastY = currentY
    },
    //触摸结束
    handletouchend: function(event) {
        if (this.data.daoding == 0) {
            return;
        }
        if (this.data.pulldown == '向下滑动') {
            this.scrollToLower2();
        }
        this.data.currentGesture = 0;
    }
})